/*
** COMPRESS.C: Compresses a text file. Use UNCOMP.C to
** restore to original form.
*/

#include <stdio.h>
#include <string.h>
#include <compress.h>

#ifdef __WATCOMC__
	#define putw _putw
#endif

BYTE inbuff[BUFSIZ];
BYTE outbuff[BUFSIZ + 200];

void main(int argc,char *argv[])
{
   FILE *istream,*ostream;
   WORD complen,uncomplen;
   NODE *rootnode;

   /* check arguments */
   if(argc != 3 || !stricmp(argv[1],argv[2])) {
      printf("Usage:\tCOMPRESS <infile> <outfile>\n");
      return;
   }

   /* open files */
   istream = fopen(argv[1],"rt");
   ostream = fopen(argv[2],"wb");
   if(istream == NULL || ostream == NULL) {
      printf("File error\n");
      return;
   }

   /* build compression code tree */
   rootnode = gettree(istream);
   if(rootnode == NULL) {
      printf("Out of memory\n");
      return;
   }

   /* set file pointer back to beginning of file */
   rewind(istream);

   /* write compressed code tree to file */
   complen = writetree(rootnode,outbuff);
   putw(complen,ostream);
   fwrite(outbuff,sizeof(BYTE),complen,ostream);

   /* compress data and write to output file */
   do {
      uncomplen = fread(inbuff,sizeof(BYTE),BUFSIZ,
         istream);
      complen = compress(inbuff,uncomplen,outbuff,
         rootnode);
      putw(uncomplen,ostream);
      putw(complen,ostream);
      fwrite(outbuff,sizeof(BYTE),complen,ostream);
   } while(uncomplen == BUFSIZ);

   /* indicate end of file */
   putw(0x00,ostream);

   fclose(istream);
   fclose(ostream);
}
